<template>
    <el-card>
        <el-form ref="queryFormRef" :inline="true" :model="queryParam" class="queryFrom">
            <el-form-item label="用户名">
                <el-input v-model="queryParam.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="真实姓名">
                <el-input v-model="queryParam.realName" placeholder="请输入真实姓名" />
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="queryParam.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="querySelective" :icon="Search">查询</el-button>
                <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card>
        <el-button type="primary" :icon="Plus" class="mb-[20px]" v-perm="'sys:user:add'"
            @click="openAddOrUpdatePage('add', null)">添加</el-button>
        <el-button type="danger" :icon="Delete" class="mb-[20px]" v-perm="'sys:user:delete'"
            @click="batchDelete()">删除</el-button>

        <el-table :data="tableData" height="calc(100vh - 285px)" max-height="calc(100vh - 285px)" stripe
            :header-cell-style="{ 'background-color': 'rgba(229, 231, 235, var(--tw-bg-opacity))' }" row-key="id"
            @selection-change="handleSelectionChange">

            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column prop="username" label="用户名" width="120px" fixed="left" />
            <el-table-column prop="realName" label="真实姓名" width="120px" fixed="left" />
            <el-table-column label="用户头像">
                <template #default="scope">
                    <el-avatar :size="50" :src="scope.row.avatar" />
                </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="260px" />
            <el-table-column prop="phone" label="手机号" width="200px" />
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    <DictTag :dictList="userSexDictList" :dictValue="scope.row.sex"></DictTag>
                </template>
            </el-table-column>
            <el-table-column prop="roleNames" label="角色" width="200px" />
            <el-table-column prop="deptName" label="部门" width="200px" />
            <el-table-column prop="postName" label="岗位" width="200px" />
            <el-table-column label="创建人" width="150px">
                <template #default="scope">
                    {{ scope.row.createByRealName }}({{ scope.row.createByUsername }})
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="200px" />
            <el-table-column label="更新人" width="150px">
                <template #default="scope">
                    {{ scope.row.updateByUsername ? `${scope.row.updateByRealName}${scope.row.updateByRealName ? ' (' +
                        scope.row.updateByUsername + ')' : ''}` : scope.row.updateByUsername || '' }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="200px" />
            <el-table-column fixed="right" label="操作" width="140px">
                <template #default="scope">
                    <el-button link type="warning" size="small" :icon="Edit" v-perm="'sys:user:update'"
                        @click="openAddOrUpdatePage('update', scope.row)">修改</el-button>
                    <el-button link type="danger" size="small" :icon="Delete" v-perm="'sys:user:delete'"
                        @click="deleteById(scope.row.id)" v-if="scope.row.username != 'admin'">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[30, 50, 100, 300, 500]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="pageSizeChange"
            @current-change="pageNumChange" />
    </el-card>
    <AddOrUpdate ref="addOrUpatePageRef" :querySelective="querySelective" :sysPostList="sysPostList"
        :sysDeptList="sysDeptList" :treeProps="treeProps" :sysRoleList="sysRoleList"></AddOrUpdate>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { queryPostSelectReq } from '@/api/sys/post/index.js'
import { queryDeptTreeReq } from '@/api/sys/dept/index.js'
import { queryRoleSelectReq } from '@/api/sys/role/index.js'
import { querySelectiveReq, deleteReq } from '@/api/sys/user/index.js'

import AddOrUpdate from '@/views/sys/user/AddOrUpdate.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import DictTag from '@/components/DictTag.vue'
import { queryDictDataListReq } from '@/api/sys/dict/data/index.js'

const treeProps = ref({
    label: "name"
})

const sysPostList = ref([])
const sysDeptList = ref([])
const sysRoleList = ref([])
const userSexDictList = ref([])
onMounted(async () => {
    Promise.all([queryPostSelectReq(), queryDeptTreeReq(), queryRoleSelectReq(),queryDictDataListReq('user_sex')])
        .then(responses => {
            if(responses[0].code == 200){
                sysPostList.value = responses[0].data
            }
            if(responses[1].code == 200){
                sysDeptList.value = responses[1].data
            }
            if(responses[2].code == 200){
                sysRoleList.value = responses[2].data
            }
            if(responses[3].code == 200){
                userSexDictList.value = responses[3].data
            }
        });

    querySelective();
})

const queryParam = reactive({
    username: '',
    phone: '',
    realName: ''
})
const tableData = ref([])
const total = ref(0)
const querySelective = async () => {
    const res = await querySelectiveReq(pageNum.value, pageSize.value, queryParam);
    if (res.code == 200) {
        tableData.value = res.data.data
        total.value = res.data.total
    }
}

const pageNum = ref(1)
const pageSize = ref(30)
const pageSizeChange = (val) => {
    pageNum.value = 1;
    pageSize.value = val;
    querySelective();
}
const pageNumChange = (val) => {
    pageNum.value = val;
    querySelective();
}

const queryFormRef = ref()
const resetQuery = () => {
    //  重置表单
    queryParam.username = ''
    queryParam.realName = ''
    queryParam.phone = ''
    queryFormRef.value?.resetFields()
    pageNumChange(1);
}

const addOrUpatePageRef = ref()
const openAddOrUpdatePage = (type, row) => {
    addOrUpatePageRef.value?.open(type, row)
}

const selectIds = ref([])
const handleSelectionChange = (val) => {
    selectIds.value = []
    val.forEach(item => {
        selectIds.value.push(item.id);
    })
    console.log("selectIds", selectIds.value)
}

const batchDelete = () => {
    if (selectIds.value.length == 0) {
        ElMessage({
            message: '请选择要删除的用户！',
            grouping: true,
            type: 'error',
        })
        return;
    }
    ElMessageBox.confirm(
        '此操作将删除选中的用户，您确定要继续吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteReq(selectIds.value).then(res => {
            if (res.code == 200) {
                ElMessage.success(res.message)
                querySelective();
            }
        })
    })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除！',
            })
        })
}

const deleteById = (id) => {
    ElMessageBox.confirm(
        '此操作将删除本用户，您确定要继续吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const ids = []
        ids.push(id)
        deleteReq(ids).then(res => {
            if (res.code == 200) {
                ElMessage.success(res.message)
                querySelective();
            }
        })
    })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除！',
            })
        })
}

const selectable = (row) => ![1].includes(row.id)
</script>

<style>
.queryFrom .el-form-item {
    margin-bottom: 0px;
}

.tableHeaderClass {
    background-color: #d3d3d3;
    /* 灰色背景 */
}
</style>